package gis.activities;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.supermap.android.commons.EventStatus;
import com.supermap.android.maps.measure.MeasureMode;
import com.supermap.android.maps.measure.MeasureParameters;
import com.supermap.android.maps.measure.MeasureResult;
import com.supermap.android.maps.measure.MeasureService;
import com.supermap.services.components.commontypes.Point2D;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import gis.dto.PhotoPoints;
import gis.network.http.UploadPhotoAndPoints;
import gis.utils.Constants;
import gis.utils.Coord;
import gis.utils.UploadPhotoPointsThread;
import gis.views.adapters.PickPointsAdatper;
import gis.views.beans.PointXY;
import managers.UIHandler;
import managers.VolleySingleton;
import model.OwnUser;

/**
 * 测算面积
 * Created by 凯 on 2015/11/25.
 */
public class ChangeGPSInfo extends UIHandler.BaseActivity {

    Button btn_back;

    ListView lv_points;
    EditText et_other;

    View btn_pick;
    View btn_upload;
    View btn_clear;

    View btn_area;

    String provider;

    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.defalut_img) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.drawable.defalut_img)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.defalut_img)  //设置图片加载/解码过程中错误时候显示的图片
//    .cacheInMemory(true)//设置下载的图片是否缓存在内存中
//    .cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中
            .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
            .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
            .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
            .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
            .build();//构建完成

    ImageView img_photo;

    View v_takePhoto;
    View v_choosePhoto;
    View v_cancel;

    View v_alert;

    PickPointsAdatper pickPointsAdatper;

    File file; // 保存图片文件
//    Bitmap bitmap;
    ArrayList<PointXY> pointXies = new ArrayList<PointXY>();

    LocationManager locationManager;


    private final static int TAKE_PHOTO_WITH_DATA = 1;

    private LocationListener locationListenner;
    private double d_longitude;
    private double d_latitude;
    private CheckBox cb;
    private Button btn_view;

    Long changTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_changegpsinfo);

        changTime = getIntent().getLongExtra("changeTime",0);
        initviews();
        initdata();
    }

    // 根据时间获取当前的数据记录
    private void initdata() {
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/getGPSByTime";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        List<PhotoPoints> points = JSON.parseArray(response, PhotoPoints.class);
                        initgpsshow(points);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MyApplication.share(),"获取数据失败，请检查网络连接并重新打开此页面",Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("time",changTime+"");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }

    // 初始化已经采集的gps数据
    private void initgpsshow(List<PhotoPoints> points) {
        boolean isSet = false;
        for (PhotoPoints p:points)
        {
            PointXY pointXY = new PointXY();
            pointXY.setX(p.getJingdu());
            pointXY.setY(p.getWeidu());
            PickPointsAdatper.ItemClass itemClass = new PickPointsAdatper.ItemClass();
            itemClass.setIsChoosed(true);
            itemClass.setPointXY(pointXY);
            pickPointsAdatper.getPointXYs().add(itemClass);

            if (!isSet)
            {
                et_other.setText(p.getRemark());
                isSet = true;
            }
        }

        pickPointsAdatper.notifyDataSetChanged();
    }

    private void initgps() {

        // 判断是否打开GPS或者网络
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!gps) {
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("提高\"我的位置\"精确度").
                    setMessage("如需获取更精确的位置服务，请您在室外时执行以下操作:\n在位置设置中打开GPS").
                    setIcon(R.drawable.location_mark2).
                    setNeutralButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                        }
                    }).
                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).
                    create();
            alertDialog.show();
            String str = "GPS没有开!";
            Log.i("GPSmeiyuukai:", str);
        }
    }

    View.OnClickListener itemclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_pick) {
                PointXY pointXY = new PointXY();

                if (d_longitude == 0 || d_latitude == 0)
                {
                    Toast.makeText(ChangeGPSInfo.this,"不能获取位置服务",Toast.LENGTH_SHORT).show();
                    return;
                }
                // 定位到加便宜后的地址，不是原始地址
                pointXY.setX(d_longitude + Constants.LONGITUDE_OFFSET);
                pointXY.setY(d_latitude + Constants.LATITUDE_OFFSET);

                System.out.println(pointXY.getX()+","+pointXY.getY());

                PickPointsAdatper.ItemClass itemClass = new PickPointsAdatper.ItemClass();
                itemClass.setIsChoosed(true);
                itemClass.setPointXY(pointXY);
                pickPointsAdatper.getPointXYs().add(itemClass);
                pickPointsAdatper.notifyDataSetChanged();
            } else if (v == btn_upload) {

                if (!check()) return;
                else {
                    new AlertDialog.Builder(ChangeGPSInfo.this).setTitle("采集坐标").
                            setMessage("采集完毕，确认上传？").setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
//                            upload();//数据上传
                            updategps();
                            //AdcpActivity.this.finish();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //清空数据
                            dialog.dismiss();
                        }

                    }).show();
                }


            } else if (v == btn_clear) {
                pickPointsAdatper.getPointXYs().clear();
                pickPointsAdatper.notifyDataSetChanged();
            } else if (v == v_choosePhoto) {

                Intent intent = new Intent();
            /* 开启Pictures画面Type设定为image */
                intent.setType("image/*");
			/* 使用Intent.ACTION_GET_CONTENT这个Action */
                intent.setAction(Intent.ACTION_GET_CONTENT);

                startActivityForResult(intent, 0x01);
                v_alert.setVisibility(View.GONE);
            } else if (v == v_takePhoto) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File filedir = new File("/sdcard/myappimg/");
                if (!filedir.exists()) {
                    filedir.mkdir();
                }

                file = new File("/sdcard/myappimg/tmep.jpg");

                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent, 0x02);
                v_alert.setVisibility(View.GONE);

            } else if (v == img_photo) {
                v_alert.setVisibility(View.VISIBLE);
            } else if (v == v_cancel) {
                v_alert.setVisibility(View.GONE);
            } else if (v == btn_back) {
                finish();
            } else if (v == btn_area) {

                ArrayList<Point2D> point2Ds = new ArrayList<Point2D>();
                for (PickPointsAdatper.ItemClass itemClass : pickPointsAdatper.getPointXYs()) {
                    if (itemClass.isChoosed())
                    {
                        Point2D point2D = new Point2D(itemClass.getPointXY().getX(), itemClass.getPointXY().getY());
                        point2Ds.add(point2D);
                    }
                }

//                Toast.makeText(MyApplication.nshare(),""+MapUtil.getGeo(point2Ds),Toast.LENGTH_SHORT).show();
//                showGeoInfo(MapUtil.getGeo(point2Ds));
                if (point2Ds.size() == 2)
                {
                    Point2D[] point2Ds1 = new Point2D[point2Ds.size()];
                    for (int j=0;j<point2Ds.size();j++)
                    {
                        Double[] doubles = Coord.Coord2(point2Ds.get(j).x,point2Ds.get(j).y);
                        Point2D point2DTmp = new Point2D(doubles[0],doubles[1]);
                        point2Ds1[j] = point2DTmp;
                    }
                    if (MyApplication.share().isNetworkAvailable())
                    {
                        Measure_distance(point2Ds1);
                    }
                    else
                    {
                        Toast.makeText(MyApplication.share(),"网络不可用，请打开网络",Toast.LENGTH_SHORT).show();
                    }
                }
                else if (point2Ds.size() > 2)
                {
                    Point2D[] point2Ds1 = new Point2D[point2Ds.size()];
                    for (int j=0;j<point2Ds.size();j++)
                    {
                        Double[] doubles = Coord.Coord2(point2Ds.get(j).x,point2Ds.get(j).y);
                        Point2D point2DTmp = new Point2D(doubles[0],doubles[1]);
                        point2Ds1[j] = point2DTmp;
                    }
                    if (MyApplication.share().isNetworkAvailable())
                    {
                        Measure_Area(point2Ds1);
                    }
                    else
                    {
                        Toast.makeText(MyApplication.share(),"网络不可用，请打开网络",Toast.LENGTH_SHORT).show();
                    }
                }

            }

        }
    };

    // 更新gps结果并上传
    private void updategps() {

        final UploadPhotoAndPoints.Upload upload = new UploadPhotoAndPoints.Upload();
        upload.setPoints(pointXies);
        OwnUser ownUser = MyApplication.getOwnUser();
        upload.setUserAccount(ownUser.getUser_NickName());
        upload.setUserName(ownUser.getUser_RealName());
        String remark = "";
        remark = et_other.getText().toString() == null ? "" : et_other.getText().toString();
        upload.setRemark(remark);


        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/gps/changeGPSInfo";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.equals("1"))
                        {

                            Toast.makeText(MyApplication.share(),"更新成功",Toast.LENGTH_SHORT).show();
                            ChangeGPSInfo.this.finish();
                        }
                        else
                        {
                            Toast.makeText(MyApplication.share(),"更新失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MyApplication.share(),"更新失败",Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map map = new HashMap();
                map.put("time",changTime+"");
                map.put("data",JSON.toJSONString(upload));
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String temp = null;
                try {
                    temp = new String(response.data, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Response.success(temp, HttpHeaderParser.parseCacheHeaders(response));
            }
        };
        VolleySingleton.getVolleySingleton(MyApplication.share()).addToRequestQueue(stringRequest);
    }


    // 面积量算结果
    public void Measure_Area(Point2D[] ptsTmp) {
        // 构造查询参数
        MeasureParameters parameters = new MeasureParameters();
//        com.supermap.services.components.commontypes.Point2D[] pts = { new com.supermap.services.components.commontypes.Point2D(23, 34), new com.supermap.services.components.commontypes.Point2D(53.55, 12.66), new com.supermap.services.components.commontypes.Point2D(73.88, 12.6),new com.supermap.services.components.commontypes.Point2D(23,34) };
        parameters.point2Ds =ptsTmp;
        MeasureService service = new MeasureService(MapShow.DEFAULT_URL);
        MyMeasureEventListener2 listener = new MyMeasureEventListener2();
        service.process(parameters, listener, MeasureMode.AREA);

    }

    // 量算监听器类
    class MyMeasureEventListener2 extends MeasureService.MeasureEventListener {
        @Override
        public void onMeasureStatusChanged(Object sourceObject, EventStatus status) {
            // 量算结果
            final MeasureResult result = (MeasureResult) sourceObject;
//            Toast.makeText(UploadPoint.this,"面积:"+result.area,Toast.LENGTH_SHORT).show();
            if (result == null) {
                Toast.makeText(MyApplication.share(),"获取面积失败",Toast.LENGTH_SHORT).show();
                return;
            }
            UIHandler.uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    new AlertDialog.Builder(ChangeGPSInfo.this).
                            setTitle("面积").
                            setMessage(result.area + "平方米")
                            .show();
                }
            });
        }
    }


    // 距离量算结果
    public void Measure_distance(Point2D[] pts) {
        // 构造查询参数
        MeasureParameters parameters = new MeasureParameters();
//        com.supermap.services.components.commontypes.Point2D[] pts = { new com.supermap.services.components.commontypes.Point2D(23, 34), new com.supermap.services.components.commontypes.Point2D(53.55, 12.66) };
        parameters.point2Ds =pts;
        MeasureService service = new MeasureService(MapShow.DEFAULT_URL);
        MyMeasureEventListener listener = new MyMeasureEventListener();
        service.process(parameters, listener,null);

    }

    // 量算监听器类
    class MyMeasureEventListener extends MeasureService.MeasureEventListener {
        @Override
        public void onMeasureStatusChanged(Object sourceObject, EventStatus status) {
            // 量算结果
            final MeasureResult result = (MeasureResult) sourceObject;

            UIHandler.uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    new AlertDialog.Builder(ChangeGPSInfo.this).
                    setTitle("距离").
                    setMessage(result.distance + "米")
                    .show();
                }
            });
        }
    }



    // 上传
    private void upload() {
        pointXies.clear();
        for (PickPointsAdatper.ItemClass itemClass : pickPointsAdatper.getPointXYs()) {
            if (itemClass.isChoosed()) {
                pointXies.add(itemClass.getPointXY());
            }
        }

        UploadPhotoAndPoints.Upload upload = new UploadPhotoAndPoints.Upload();
        upload.setPoints(pointXies);
        OwnUser ownUser = MyApplication.getOwnUser();
        upload.setUserAccount(ownUser.getUser_NickName());
        upload.setUserName(ownUser.getUser_RealName());
        String remark = "";
        remark = et_other.getText().toString() == null ? "" : et_other.getText().toString();
        upload.setRemark(remark);
        UploadPhotoAndPoints uploadPhotoAndPoints = new UploadPhotoAndPoints(file, upload);
        uploadPhotoAndPoints.setOriginimg(cb.isChecked());

        UploadPhotoPointsThread uploadPhotoPointsThread = new UploadPhotoPointsThread(uploadPhotoAndPoints);
        uploadPhotoPointsThread.setRunnable(new Runnable() {
            @Override
            public void run() {
                closeDialog();
            }
        });
        showDialog();
        new Thread(uploadPhotoPointsThread).start();
    }

    // 检查
    private boolean check() {
//        if (file == null) {
//            Toast.makeText(MyApplication.share(), "没有照片", Toast.LENGTH_SHORT).show();
//            return false;
//        }

        pointXies.clear();
        for (PickPointsAdatper.ItemClass itemClass : pickPointsAdatper.getPointXYs()) {
            if (itemClass.isChoosed()) {
                pointXies.add(itemClass.getPointXY());
            }
        }

        if (pointXies.isEmpty()) {
            Toast.makeText(MyApplication.share(), "没有坐标", Toast.LENGTH_SHORT).show();
            return false;
        }

        for(int i = 1;i< pointXies.size();i++)
        {
            PointXY pointXY = pointXies.get(i);
            Result result = isPointExists(pointXY,pointXies,i-1);
            if (result != null && result.isIn)
            {
                Toast.makeText(MyApplication.share(),"选中的第"+i+"个点与第"+result.position+"个点不能相同！",Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        return true;
    }

    // 点是否在集合中
    private Result isPointExists(PointXY pointXY,ArrayList<PointXY> pointXies,int to)
    {
        for(int i = 0;i<= to;i++)
        {
            PointXY temp  = pointXies.get(i);
            if (temp.getX() == pointXY.getX() && temp.getY() == pointXY.getY())
            {
                Result result = new Result();
                result.isIn = true;
                result.position = i;
                return result;
            }
        }
        return null;
    }


    // 上个方法的结果
    static class Result
    {
        public boolean isIn; // 是否在
        public int position;   // 位置

    }

    // 点击打开历史
    View.OnClickListener viewHistroy = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ChangeGPSInfo.this.startActivity(new Intent(MyApplication.share(),ViewTime.class));
        }
    };


    // 初始化
    private void initviews() {
        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(itemclick);
        et_other = (EditText) findViewById(R.id.id_et_other);
        lv_points = (ListView) findViewById(R.id.id_lv_points);
        btn_pick = findViewById(R.id.id_btn_pick);
        btn_upload = findViewById(R.id.id_btn_upload);
        btn_clear = findViewById(R.id.id_btn_clear);
        btn_area = findViewById(R.id.id_btn_area);
        btn_area.setOnClickListener(itemclick);
        img_photo = (ImageView) findViewById(R.id.id_img_take);
        img_photo.setOnClickListener(itemclick);
        v_takePhoto = findViewById(R.id.id_v_takePhoto);
        v_takePhoto.setOnClickListener(itemclick);
        v_alert = findViewById(R.id.id_v_alert);
        v_cancel = findViewById(R.id.id_v_cancel);
        v_cancel.setOnClickListener(itemclick);
        btn_pick.setOnClickListener(itemclick);
        btn_upload.setOnClickListener(itemclick);
        btn_clear.setOnClickListener(itemclick);
        pickPointsAdatper = new PickPointsAdatper();
        lv_points.setAdapter(pickPointsAdatper);

        cb = (CheckBox) findViewById(R.id.id_cb);
        btn_view = (Button) findViewById(R.id.id_btn_view);
        btn_view.setOnClickListener(viewHistroy);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0)
            return;
        if (requestCode == 0x02) {
            if (resultCode == RESULT_OK) {
                if (file != null) {
                    ImageLoader.getInstance().displayImage("file:///mnt/" + file.getAbsolutePath(),img_photo, options, listener);

                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 创建LocationManager对象
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        initgps();
        boolean isGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isGps)
        {
            provider = LocationManager.GPS_PROVIDER;
        }
        else
        {
            provider = LocationManager.NETWORK_PROVIDER;
        }
        locationManager.requestLocationUpdates(provider, 0, 1, locationListenner = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 当GPS定位信息发生改变时，更新位置
                updateLocation(location);
            }

            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(locationListenner);
    }

    // 更新坐标
    public void updateLocation(Location newLocation) {
        if (newLocation != null) {
            d_longitude = newLocation.getLongitude();
            d_latitude = newLocation.getLatitude();
        } else {

        }
    }

    // 图片加载
    ImageLoadingListener listener = new SimpleImageLoadingListener() {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            Log.i("imgUri", imageUri);
        }
    };
}
